package org.six11.olive3.server;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
import static org.six11.olive3.server.WebActionServlet.*;

import org.six11.olive3.util.ImageUtil;
import org.six11.util2.Debug;

/**
 * 
 * 
 * @author Gabe Johnson <johnsogg@cmu.edu>
 */
public class RawPenBroker extends HttpServlet {

  private DatabaseThing dbThing;

  public RawPenBroker() throws NamingException {
    Context env = (Context) new InitialContext().lookup("java:comp/env");
    dbThing = new DatabaseThing((DataSource) env.lookup(InkBroker.DATASOURCE_NAME));
  }

  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException,
      IOException {
    String penData = null;
    String sketchID = (String) req.getParameter(PARAM_SKETCH_ID);
    if (sketchID != null) {
      Map<String, String> vals = dbThing.getRow(SqlStrings.FIND_SKETCH, sketchID);
      penData = vals.get("data");
    }

    if (penData != null && penData.length() > 0) {
      resp.setContentType("text/plain");
      resp.setHeader( "Content-Disposition", "attachment; filename=\"" + sketchID + ".sketch\"" );
      ServletOutputStream ros = resp.getOutputStream();
      ros.print(penData);
      ros.close();
    } else if (sketchID == null) {
      resp.sendError(HttpServletResponse.SC_BAD_REQUEST);
    } else {
      resp.sendError(HttpServletResponse.SC_NOT_FOUND);
    }
  }

  @Override
  protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException,
      IOException {
    this.doGet(req, resp);
  }

  /**
   * The following function was taken from
   * http://www.java-tips.org/java-se-tips/java.io/reading-a-file-into-a-byte-array.html.
   */
  public static byte[] getBytesFromFile(File file) throws IOException {
    InputStream is = new FileInputStream(file);
    long length = file.length();

    if (length > Integer.MAX_VALUE) {
      return new byte[0];
    }
    byte[] bytes = new byte[(int) length];
    int offset = 0;
    int numRead = 0;
    while (offset < bytes.length && (numRead = is.read(bytes, offset, bytes.length - offset)) >= 0) {
      offset += numRead;
    }
    if (offset < bytes.length) {
      throw new IOException("Could not completely read file " + file.getName());
    }
    is.close();
    return bytes;
  }

  private static void bug(String what) {
    Debug.out("ImageBroker", what);
  }
}
